<template>
  <picker-view indicator-style="height: 40px;" :value="checkValue" @change="bindChange" class="picker-view">
    <picker-view-column>
      <view class="item" v-for="(item,index) in nums" :key="index">{{item}}{{ Number(item) ? afterLabel : ''}}</view>
    </picker-view-column>
    <picker-view-column>
      <view class="divider">到</view>
    </picker-view-column>
    <picker-view-column>
      <view class="item" v-for="(item,index) in nums" :key="index">{{item}}{{ Number(item) ? afterLabel : ''}}</view>
    </picker-view-column>
  </picker-view>
</template>

<script setup>
import { readuceNumFn } from "@/utils";
const props = defineProps({
  mode: {
    type: String,
    default: "",
  },
  formData: {
    type: Object,
    default: () => {},
  },
});

const checkValue = ref([0, 0, 9999]);
const isChange = ref(false);
const pickerConfig = reactive({
  age: {
    label: "岁",
    range: [60, 18],
  },
  height: {
    label: "cm",
    range: [200, 140],
  },
});

const afterLabel = computed(() => pickerConfig[props.mode]?.label);
const nums = computed(() => {
  const range = pickerConfig[props.mode]?.range || [];
  const maxNum = range[0];
  const minNum = range[1];
  const result = readuceNumFn(minNum, maxNum, []);

  result.unshift("不限");
  return result;
});

// 获取当前选中的数据
const currentNum = computed(() => {
  const data = props.formData[props.mode];
  const label = afterLabel.value;
  if (data && data != "不限") {
    const arr = data.split("到");
    if (arr.length) {
      const one = Number(arr[0].split(label)[0]);
      const two = Number(arr[1].split(label)[0]);
      const pIndex = nums.value.findIndex((v) => v == one);
      const cIndex = nums.value.findIndex((v) => v == two);
      return [pIndex, 0, cIndex];
    }
  }
  return [0, 0, 0];
});

// 滑动选择
const bindChange = (e) => {
  isChange.value = true;
  const val = e.detail.value;
  getNum(val);
};

// 赋值
const getNum = (val = []) => {
  let v1 = nums.value[val[0]];
  let v2 = nums.value[val[2]];

  if (v1 && v2) {
    if (v1 == "不限" && v2 == "不限") {
      props.formData[props.mode] = "不限";
    } else {
      if (v1 == "不限") {
        v1 = nums.value[1];
      }
      if (v2 == "不限") {
        v2 = nums.value[nums.value.length - 1];
      }

      props.formData[props.mode] = `${v1}${afterLabel.value}到${v2}${afterLabel.value}`;
    }
  }
};

// 初始化
const init = () => {
  const val = currentNum.value;
  nextTick(() => {
    checkValue.value = val;
    getNum(val);
  });
};

onMounted(() => {
  init();
});
</script>

<style lang=scss scoped>
.picker-view {
  width: 100%;
  height: 560rpx;
  margin: 60rpx 0;
}
.divider {
  color: #999;
  font-size: 40rpx;
  font-weight: 400;
  line-height: 40px;
}
.item {
  line-height: 80rpx;
  text-align: center;
  font-weight: bold;
  font-size: 40rpx;
}
</style>